package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

const (
	signVersion = "auth-v2"

	ak      = "19b8c5d072d00c3439ececeb96cc6703"
	sk      = "c65911deeeb03c1a48c108d0a1e2bf56"
	baseURL = "https://iaas-videoarch.bytedance.com"
)

type HClient struct {
	baseURL string
	*http.Client
}

func NewHTTPClient(baseURL string) *HClient {
	return &HClient{
		baseURL: baseURL,
		Client:  &http.Client{},
	}
}

func (client *HClient) MakeRequest(verb, reqURL string, headers map[string]string, data *bytes.Buffer) (stat int, resp string, err error) {
	url := client.baseURL + reqURL
	request, err := http.NewRequest(verb, url, data)
	if err != nil {
		return
	}

	for k, v := range headers {
		request.Header.Set(k, v)
	}

	response, err := client.Do(request)
	if err != nil {
		return
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	return response.StatusCode, string(body), err
}

func sha256HMAC(key []byte, data []byte) []byte {
	mac := hmac.New(sha256.New, key)
	mac.Write(data)
	return []byte(fmt.Sprintf("%x", mac.Sum(nil)))
}

func Sign(ver string, ak string, sk string, body []byte) string {
	expiration := 1800
	signKeyInfo := fmt.Sprintf("%s/%s/%d/%d", ver, ak, time.Now().Unix(), expiration)
	signKey := sha256HMAC([]byte(sk), []byte(signKeyInfo))
	signResult := sha256HMAC(signKey, body)
	return fmt.Sprintf("%v/%v", signKeyInfo, string(signResult))
}

func main() {
	ips := []string{}
	type Item struct {
		ParentID string `json:"parent_id,omitempty"`
	}
	type Data struct {
		Items []Item `json:"items,omitempty"`
	}
	type Response struct {
		StatusCode string `json:"status_code,omitempty"`
		Data       Data   `json:"data,omitempty"`
	}
	for _, ip := range ips {
		httpClient := NewHTTPClient(baseURL)
		//	query := "ip=10.172.103.232&with_parent=true"
		query := fmt.Sprintf("ip=%s", ip)
		sig := Sign(signVersion, ak, sk, []byte(query))
		_, resp, _ := httpClient.MakeRequest("GET", "/dcm/api/v1/compute_units"+"?"+query, map[string]string{"Agw-Auth": sig}, bytes.NewBuffer([]byte("")))
		// fmt.Println(resp)
		m := Response{}
		json.Unmarshal([]byte(resp), &m)
		fmt.Println(m.Data.Items[0].ParentID)
	}
}
